package com.dcbeida.activity.store;

import android.app.DatePickerDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.dcbeida.MyApplication;
import com.dcbeida.R;
import com.dcbeida.activity.BaseActivity;
import com.dcbeida.activity.CaptureActivity;
import com.dcbeida.activity.source_unit.SourceActivity;
import com.dcbeida.adapter.StoreAdapter;
import com.dcbeida.bean.DrugInfo;
import com.dcbeida.bean.Image;
import com.dcbeida.bean.SourceBean;
import com.dcbeida.callback.PhotoCallBack;
import com.dcbeida.utils.CameraUtil;
import com.dcbeida.utils.Constants;
import com.dcbeida.utils.GetPhotoFromAlbum;
import com.dcbeida.utils.GifSizeFilter;
import com.dcbeida.utils.PutAliyObject;
import com.dcbeida.utils.Utils;
import com.dcbeida.utils.permission.AndPermission;
import com.dcbeida.utils.permission.PermissionListener;
import com.dcbeida.utils.permission.Rationale;
import com.dcbeida.utils.permission.RationaleListener;
import com.dcbeida.widget.PhotoViewShow;
import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.MimeType;
import com.zhihu.matisse.engine.impl.GlideEngine;
import com.zhihu.matisse.filter.Filter;
import com.zhihu.matisse.internal.entity.CaptureStrategy;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.Locale;

import butterknife.Bind;
import butterknife.ButterKnife;

import static com.dcbeida.utils.Constants.PERMISSION_CAMERA;
import static com.dcbeida.utils.Constants.PERMISSION_WRITE_EXTERNAL_STORAGE;
import static com.dcbeida.utils.Constants.REQUEST_CODE_CHOOSE;

/**
 * 药品入库
 */
public class StoreActivity extends BaseActivity implements View.OnClickListener, StoreContract.View {


    @Bind(R.id.img_back)
    ImageView img_back;


    @Bind(R.id.tv_time1)
    TextView tv_time1;

    @Bind(R.id.tv_time2)
    TextView tv_time2;


    @Bind(R.id.tv_type)
    TextView tv_type;

    @Bind(R.id.tv_all2)
    TextView tv_all2;

    @Bind(R.id.lin_add)
    LinearLayout lin_add;

    @Bind(R.id.lin_confim)
    LinearLayout lin_confim;

    @Bind(R.id.tv_confim)
    TextView tv_confim;

    @Bind(R.id.lin_time2)
    LinearLayout lin_time2;

    @Bind(R.id.tvAddCode)
    TextView tvAddCode;


    @Bind(R.id.ll_lhdw)
    LinearLayout ll_lhdw;
    @Bind(R.id.tv_lhdw)
    TextView tv_lhdw;
    @Bind(R.id.et_price)
    EditText et_price;

    String from = "";
    int fromID = 0;
    String invoiceMoney = "";

    public Handler iHandler;
    @Bind(R.id.recyclerview)
    RecyclerView recyclerview;
    private String localUrl = "";//选取的本地图片url
    private String shdurl = "";//送货单url

    LayoutInflater inflater;

    private String time2 = "";

    private StoreContract.Present mPresent;
    private StoreAdapter storeAdapter;
    private static final String[] requestPermissions = {
            PERMISSION_CAMERA,
            PERMISSION_WRITE_EXTERNAL_STORAGE
    };
    private List<String> obtainPathResult;//本地图片地址

    private ArrayList<String> imgUrl;//服务器图片地址

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_store;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initListeners();
        initParams();
        initdata();
        inflater = LayoutInflater.from(this);

        addMessageHandler();

        mPresent.getSourcelInfo("");
    }

    private void initListeners() {
        img_back.setOnClickListener(this);
        lin_confim.setOnClickListener(this);
        tv_confim.setOnClickListener(this);
        lin_time2.setOnClickListener(this);
        ll_lhdw.setOnClickListener(this);
    }

    private void initdata() {
        tv_time1.setText(Utils.getNowTime());
        obtainPathResult = new ArrayList<String>();
        imgUrl = new ArrayList<String>();
        LinearLayoutManager layoutManager = new LinearLayoutManager(mContext);
        layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        recyclerview.setLayoutManager(layoutManager);
        //如果可以确定每个item的高度是固定的，设置这个选项可以提高性能
        recyclerview.setHasFixedSize(true);
        storeAdapter = new StoreAdapter(mContext);
        recyclerview.setAdapter(storeAdapter);
        storeAdapter.setOnItemClickListener(new StoreAdapter.OnRecyclerViewItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                if (position == storeAdapter.mUris.size()) {
                    //权限申请
                    AndPermission.with(mContext)
                            .requestCode(100)
                            .permission(requestPermissions)
                            .rationale(rationaleListener)
                            .send();
                } else {
                    //传递当前点击的图片的位置、图片路径集合
                    Bundle bundle = new Bundle();
                    bundle.putInt("position", position);
                    bundle.putStringArrayList("mImages", imgUrl);
                    showActivity(PhotoViewShow.class, bundle);
                }
            }

        });

        storeAdapter.setOnItemDelClickListener(new StoreAdapter.OnRecyclerViewItemDelClickListener() {
            @Override
            public void onItemDelClick(View view, int position) {
                obtainPathResult.remove(position);
                imgUrl.remove(position);
                storeAdapter.setData(imgUrl);
            }
        });

    }

    private void initParams() {
        mPresent = new StorePresenter(this, this);
    }

    private RationaleListener rationaleListener = new RationaleListener() {
        @Override
        public void showRequestPermissionRationale(int requestCode, Rationale rationale) {
            rationale.resume();
        }
    };

    private PermissionListener listener = new PermissionListener() {
        @Override
        public void onSucceed(int requestCode, List<String> grantPermissions) {
            Matisse.from(mContext)
                    .choose(MimeType.ofAll(), false)
                    .countable(true)
                    .capture(true)
                    .captureStrategy(new CaptureStrategy(true, "com.dcbeida.utils.GifSizeFilter"))
                    .maxSelectable(Constants.MAX_IMAGE_SIZE - imgUrl.size())
                    .addFilter(new GifSizeFilter(320, 320, 5 * Filter.K * Filter.K))
                    .gridExpectedSize(getResources().getDimensionPixelSize(R.dimen.grid_expected_size))
                    .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT)
                    .thumbnailScale(0.85f)
                    .imageEngine(new GlideEngine())
                    .forResult(REQUEST_CODE_CHOOSE);
        }

        @Override
        public void onFailed(int requestCode, List<String> deniedPermissions) {

        }
    };

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        AndPermission.onRequestPermissionsResult(requestCode, permissions, grantResults, listener);
    }

    @Override
    public void setQuantity(int count, int quantity) {
        tv_type.setText(count + "");
        tv_all2.setText(quantity + "");
    }

    @Override
    public String getRkDate() {
        return tv_time1.getText().toString();
    }

    @Override
    public String getFhDate() {
        return time2;
    }

    @Override
    public void confimSuccess() {
        finish();
    }

    @Override
    public void showList(ArrayList<SourceBean> list) {
        if (list == null || list.size() == 0) {
            //            from = "";
            //            fromID = 0;
            //            tv_lhdw.setText(R.string.qxz);
        } else {
            SourceBean obj = list.get(0);
            from = obj.getProvidername();
            fromID = obj.getProviderid();
            tv_lhdw.setText(from);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.img_back:
                finish();
                break;
            case R.id.lin_confim:
                Bundle b = new Bundle();
                b.putInt("type", CaptureActivity.TYPE_RE);
                showActivityForResult(CaptureActivity.class, b, Constants.RESULT_CAPTER);
                break;
            case R.id.tv_confim:
                if (!mPresent.isDrugInfoList()) {
                    showTip("请扫码入库");
                    return;
                }
                if (et_price.getText().toString().trim().length() != 0)
                    invoiceMoney = Utils.dFormat(Double.parseDouble(et_price.getText().toString().trim()));

                shdurl = "";
                if (imgUrl.size() > 0) {
                    for (int i = 0; i < imgUrl.size(); i++) {
                        if (i != 0 && i != imgUrl.size()) {
                            shdurl += "," + imgUrl.get(i);
                        } else {
                            shdurl += imgUrl.get(i);
                        }
                    }
                }

                new AlertDialog.Builder(this).setMessage(R.string.message)
                        .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }
                        }).setPositiveButton(R.string.confim, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        mPresent.addstockinlog(from, fromID, invoiceMoney, shdurl);
                    }
                }).show();


                break;
            case R.id.lin_time2:
                Calendar d = Calendar.getInstance(Locale.CHINA);
                Date myDate = new Date();
                d.setTime(myDate);
                int year = d.get(Calendar.YEAR);
                int month = d.get(Calendar.MONTH);
                int day = d.get(Calendar.DAY_OF_MONTH);
                DatePickerDialog datePickerDialog = new DatePickerDialog(this,
                        new DatePickerDialog.OnDateSetListener() {
                            @Override
                            public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                                Log.i("fancl", "year:" + year + "//monthOfYear:" + monthOfYear + "//dayOfMonth:" + dayOfMonth);
                                Calendar cal = new GregorianCalendar(year, monthOfYear, dayOfMonth);
                                String pattern = "yyyy-MM-dd";
                                SimpleDateFormat dateFormat = new SimpleDateFormat(pattern);
                                time2 = dateFormat.format(cal.getTime());
                                tv_time2.setText(time2);
                            }
                        }, year, month, day);
                datePickerDialog.show();
                break;

            case R.id.ll_lhdw:
                b = new Bundle();
                showActivityForResult(SourceActivity.class, b, Constants.HOSPITAL_TYPE);
                break;
            //            case R.id.lin_shd:
            //                DialogUtils.showDialog(StoreActivity.this, new DialogCarmerListener() {
            //                    @Override
            //                    public void onAlbum() {
            //                        GetPhotoFromAlbum.ChooseWay(StoreActivity.this,
            //                                CameraUtil.PHOTO_PICKED_WITH_DATA);
            //                    }
            //
            //                    @Override
            //                    public void onPhotograph() {
            //
            //                        GetPhotoFromAlbum.ChooseWay(StoreActivity.this,
            //                                CameraUtil.CAMERA_WITH_DATA);
            //                    }
            //                });
            //                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Log.i(StoreActivity.class.getName(), "#########requestCode:" + requestCode + ";######resultCode:" + resultCode);
        if (resultCode == RESULT_OK && requestCode == Constants.RESULT_CAPTER) {
            String code = data.getStringExtra("code");
            Log.i(StoreActivity.class.getName(), "---" + code);
            mPresent.addstockindrugcodes(code);
        } else if ((requestCode == CameraUtil.PHOTO_PICKED_WITH_DATA ||
                requestCode == CameraUtil.CAMERA_WITH_DATA ||
                requestCode == CameraUtil.CAMERA_COMPLETE) && resultCode == RESULT_OK) {//获取照片

            GetPhotoFromAlbum.GetPhoto(StoreActivity.this, requestCode, data, false, mPhotoCallBack);

        } else if (requestCode == Constants.HOSPITAL_TYPE && resultCode == RESULT_OK) {//选择来货单位
            Bundle bundle = data.getExtras();
            if (null != bundle) {
                if (bundle.containsKey("sourceBean")) {
                    SourceBean sourceBean = (SourceBean) bundle.getSerializable("sourceBean");
                    fromID = sourceBean.getProviderid();
                    from = sourceBean.getProvidername();
                    tv_lhdw.setText(from);
                }
            }

        } else if (requestCode == REQUEST_CODE_CHOOSE && resultCode == RESULT_OK) {

            obtainPathResult.addAll(Matisse.obtainPathResult(data));

            updateImg(Matisse.obtainPathResult(data));

        }
    }

    private ProgressDialog dialog;

    private void updateImg(List<String> obtainPathResult) {
        dialog = new ProgressDialog(mContext, R.style.myDialogTheme);
        dialog.show();
        View layout = View.inflate(mContext, R.layout.progress, null);
        TextView tv_tip = (TextView) layout.findViewById(R.id.tv_tip);
        tv_tip.setText(R.string.zzsc);
        dialog.setContentView(layout);
        Window win = dialog.getWindow();
        win.setGravity(Gravity.CENTER);
        // 弹出对话框时，底部窗体，不变暗。
        WindowManager.LayoutParams lp = win.getAttributes();
        lp.width = (int) (MyApplication.widthPixels * 0.85);
        win.setAttributes(lp);
        dialog.setCancelable(false);
        dialog.setCanceledOnTouchOutside(false);

        dialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
            @Override
            public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
                    if (null != dialog) {
                        dialog.dismiss();
                        return true;
                    }
                }
                return false;
            }
        });

        GetPhotoFromAlbum.compressImageByQualityList(obtainPathResult, mContext, iHandler);
    }

    @Override
    public void showTip(String msg) {
        if (msg.equalsIgnoreCase("ok")) {
            sendBroadcast(new Intent(Constants.RECEIVER_STOCK_FRESH));
            super.showTip(getString(R.string.rkcg));
        } else {
            super.showTip(msg);
        }
    }


    @Override
    public void addItem(DrugInfo info) {
        if (info.getQuantity() > 0) {
            tvAddCode.setText(R.string.againrk222);
        } else {
            tvAddCode.setText(R.string.againrk);
        }

        View view = inflater.inflate(R.layout.activity_inventory_item, null);
        TextView tv_name_numb = ButterKnife.findById(view, R.id.tv_name_numb);
        TextView tv_itemAll = ButterKnife.findById(view, R.id.tv_itemAll);
        tv_name_numb.setText(getString(R.string.name_numb, info.getDrugname(), info.getDrugcode()));
        tv_itemAll.setText(info.getQuantity() + "");
        lin_add.addView(view);
    }


    @Override
    public void addItem(int pos, DrugInfo info, int head_pos, DrugInfo headInfo) {
        LinearLayout itemView = (LinearLayout) LayoutInflater.from(mContext).inflate(R.layout.has_big_title_with_item, null);
        LinearLayout lin_item_head = (LinearLayout) itemView.findViewById(R.id.lin_item_head);
        TextView tv_yp_name = (TextView) itemView.findViewById(R.id.tv_yp_name);
        TextView tv_count = (TextView) itemView.findViewById(R.id.tv_count);
        TextView tv_ph = (TextView) itemView.findViewById(R.id.tv_ph);
        TextView tv_yxq = (TextView) itemView.findViewById(R.id.tv_yxq);
        TextView tv_bh = (TextView) itemView.findViewById(R.id.tv_bh);
        TextView tv_box = (TextView) itemView.findViewById(R.id.tv_box);

        View headView = lin_add.getChildAt(head_pos);
        if (headView != null) {
            TextView tv_count_head = (TextView) headView.findViewById(R.id.tv_count);
            tv_count_head.setText(headInfo.getCount() + "");
        } else {
            tv_count.setText(headInfo.getCount() + "");
        }

        tv_yxq.setText(info.getExpiredate());
        tv_bh.setText(info.getDrugcode());
        tv_box.setText(info.getQuantity() + "");
        tv_ph.setText(info.getBatchnumber());
        tv_yp_name.setText(headInfo.getDrugname());

        if (info.isFirst()) {
            lin_item_head.setVisibility(View.VISIBLE);
        } else
            lin_item_head.setVisibility(View.GONE);

        lin_add.addView(itemView, pos);

        if (lin_add.getChildCount() > 0) {
            tvAddCode.setText(R.string.againrk222);

        }
    }


    @Override
    public void setPresenter(StoreContract.Present presenter) {

    }


    PhotoCallBack mPhotoCallBack = new PhotoCallBack() {
        @Override
        public void Success(final String path) {
            Log.i("fancl", "-----path" + path);
            GetPhotoFromAlbum.compressImageByQuality(path, StoreActivity.this, iHandler);//压缩图片

        }

        @Override
        public void Failed(String errormsg) {
            showTip("失败" + errormsg);
        }
    };


    /**
     * 处理接收消息
     */
    private void addMessageHandler() {
        iHandler = new Handler() {
            public void handleMessage(Message msg) {
                try {
                    switch (msg.what) {
                        case Constants.UploadSuccess://阿里云上传图片成功
                            Image img = (Image) msg.obj;
                            //members.setHeadpicpath(img.getImagepath());

                            shdurl = img.getImagepath();
                            Log.i("swt", "shdurl = " + shdurl);
                            imgUrl.add(img.getImagepath());
                            if (imgUrl.size() == obtainPathResult.size()) {
                                dialog.dismiss();
                                storeAdapter.setData(imgUrl);
                            }

                            //                            img_shd.setImageBitmap(CameraUtil.fitSizeImg(localUrl));


                            break;

                        case Constants.UploadFailed://阿里云上传图片失败
                            //                            members.setHeadpicpath("");
                            shdurl = "";
                            //                            img_shd.setImageResource(R.drawable.photograph_icon);
                            dialog.dismiss();
                            showTip("上传图片失败");
                            break;
                        case 100://开始阿里云上传
                            shdurl = "";
                            //                            img_shd.setImageResource(R.drawable.photograph_icon);

                            //showTip("开始上传图片");
                            localUrl = (String) msg.obj;
                            new Thread(new Runnable() {
                                @Override
                                public void run() {
                                    new PutAliyObject(MyApplication.oss, Constants.imgBucket, Utils.getOKey2(), localUrl, iHandler).asyncPutObjectFromLocalFile();
                                }
                            }).start();
                            break;

                        default:

                            break;
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                    Log.e("error.store", e.toString());
                }
                super.handleMessage(msg);
            }
        };
    }

}
